package org.ibetyoudid.adjustremote;

import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.view.KeyEvent;

public class RemoteAdjuster extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
		//if there is no event, just return.
		if (event == null || (!Params.TRANSLATE_ENABLED)) {
			return;
		}
		//TODO: if we are in pause, then maybe don't translate events. that way we can use both volume and next/prev...
		// or better use another lut. (the E160 has the prev. on to and the next on bottom if earplus are in, very stragen...
		Map<Integer,Integer> lut = Params.MY_MAP;
		Integer cur_key_code = new Integer(event.getKeyCode());
		AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		if(am.isMusicActive()
				//&& (!Params.ONLY_TRANSLATE_WHILE_PLAYING)
		) {
			//let's see if we have a mapping for the current key
			if(lut.containsKey(cur_key_code)) {
				// Abort the broadcast.  No one will ever believe you.
				abortBroadcast();
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					int tranlated_code = lut.get(cur_key_code).intValue();
					MyLogger.logTranslate(context, cur_key_code.intValue(),tranlated_code);
					
					boolean adjustVolume = false;
					int direction = -1;
					//what should we do next
					switch (tranlated_code) {
						case KeyEvent.KEYCODE_VOLUME_DOWN:
						{
							adjustVolume = true;
							direction = AudioManager.ADJUST_LOWER;
							break;
						}
						case KeyEvent.KEYCODE_VOLUME_UP:
						{
							adjustVolume = true;
							direction = AudioManager.ADJUST_RAISE;
							break;
						}
					}
					//TODO: Emit a volume up/down keypress instead of just doing it
					if(adjustVolume) {
						am.adjustVolume(direction, AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND );
						
					}
					/*
					//for reference, this is the simple version
					AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
					if(tranlated_code == KeyEvent.KEYCODE_VOLUME_DOWN) {
						am.adjustVolume  (AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI );
					} else if(tranlated_code == KeyEvent.KEYCODE_VOLUME_UP) {
						am.adjustVolume  (AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI );
					}
					*/
				}
			}
		}
	}
}
